import axios from "axios";
import constant from "./constant";
//处理url参数
import qs from "qs";

import store from "../store";
import {Message} from 'element-ui';
import router from "../router"

axios.defaults.baseURL = constant.baseURL;


// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    let statusCode = response.data.code
    if (statusCode === 401) {
        refreshToken()
    } else if (statusCode === 300) {
        store.commit("currentAdmin", {});
        localStorage.removeItem("adminToken");
        return response;
    } else {
        return response;
    }
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

/**
 * 刷新token
 */
function refreshToken() {
    if (localStorage.getItem('adminToken')) {
        axios({
            url: '/refreshToken',
            headers: {"Authorization": localStorage.getItem("adminToken")},
            method: 'get',
            params: {},
        }).then(res => {
            if (res.data.code === 200) {
                localStorage.setItem('adminToken', res.data.data)
                window.location.reload()
            } else if (res.data.code === 500) {
                router.push('/verify')
            } else {
                Message({
                    message: res.data.msg,
                    type: 'error'
                })
            }
        })
    } else {
        router.push('/verify')
    }

}

export default {
    request(option) {
        let contentType
        if (option.contentType) {
            contentType = option.contentType
        } else {
            contentType = "application/json;charset=UTF-8"
        }

        return new Promise((resolve, reject) => {
            axios({
                url: option.url,
                method: option.method,
                headers: {
                    "Authorization": localStorage.getItem("adminToken"),
                    "Content-Type": contentType
                },
                params: option.method === 'get' ? option.data : {},
                data: option.data
            }).then(res => {
                resolve(res.data);
            }).catch(err => {
                reject(err);
            });
        })
    },
}
